//修改支付密码弹窗

import React, { useState, useEffect, useMemo } from 'react';
import {
  Form,
  Input,
  Button,
  Row,
  Col,
  Steps,
  message,
  Radio,
  Select,
  Tooltip,
} from 'antd';
import {
  bankSearch,
  bankCode,
  bankCard,
  payment,
  paymentBinding,
} from '../../service';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
const { Step } = Steps;
const { Option } = Select;

const layout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 12,
  },
};

const accountTypeMap = {
  2: '0',
  3: '1',
};

const BankCardModal = ({
  bankCardSwitch,
  accountExtend = {},
  userAccountType = {},
  bankCardClose,
  pageInit,
  accountMsg = {}, //商户绑卡的参数需要
}) => {
  const [form] = Form.useForm();
  // 步骤条索引
  const [current, setCurrent] = useState(0);
  // 类型
  const [type, setType] = useState(0);
  // 开户行下拉
  const [list, setList] = useState([]);
  const [second, setSecond] = useState(0);
  const [spinning, setSpinning] = useState(false);

  useEffect(() => {
    if (bankCardSwitch && !list.length) {
      getList();
    }
  }, [bankCardSwitch]);

  useEffect(() => {
    if (bankCardSwitch) {
      form.resetFields();
    }
  }, [bankCardSwitch, current, type]);

  //见证宝是否是老用户(不能绑卡)
  const isOldAccount = useMemo(() => {
    if (
      userAccountType?.hasOpenAccount == 1 &&
      userAccountType?.enterpriseAuthModifyState == 1
    ) {
      return true;
    }
    return false;
  }, [userAccountType]);

  // 获取开户行下拉
  const getList = async () => {
    const res = await bankSearch({
      bankName: '',
    });
    if (res.success) {
      const { data } = res;
      setList(data);
    } else {
      setList([]);
    }
  };

  const cardFrom = () => {
    if (type == 0) {
      return (
        <Form
          {...layout}
          name="pay-one"
          form={form}
          initialValues={{
            companyName: accountExtend?.licenseName,
            companyGlobalId: accountExtend?.socialCreditCode,
            name: accountExtend?.userName,
            idNumber: accountExtend?.idCard,
            phone: accountExtend?.mobile,
          }}
        >
          <Form.Item
            label="营业执照名称"
            name="companyName"
            rules={[
              {
                required: true,
                message: '请输入请输入营业执照名称',
              },
            ]}
          >
            <Input placeholder="请输入营业执照名称" autoComplete="off" />
          </Form.Item>

          <Form.Item
            label="社会统一信用代码"
            name="companyGlobalId"
            rules={[
              {
                required: true,
                message: '请输入社会统一信用代码',
              },
            ]}
          >
            <Input placeholder="请输入社会统一信用代码" autoComplete="off" />
          </Form.Item>

          <Form.Item
            label="法人姓名"
            name="name"
            rules={[
              {
                required: true,
                pattern: /^[\u4E00-\u9FA5A-Za-z\·•]+$/,
                message: '请输入正确的法人姓名',
              },
            ]}
          >
            <Input placeholder="请输入法人姓名" autoComplete="off" />
          </Form.Item>

          <Form.Item
            label="身份证号"
            name="idNumber"
            rules={[
              {
                required: true,
                pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                message: '请输入身份证号',
              },
            ]}
          >
            <Input placeholder="请输入身份证号" autoComplete="off" />
          </Form.Item>

          <Form.Item
            label="银行预留手机号"
            name="phone"
            rules={[
              {
                required: true,
                // pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                message: '请输入正确的手机号!',
              },
            ]}
          >
            <Input placeholder="请输入银行预留手机号" />
          </Form.Item>

          <Form.Item
            label="开户银行"
            name="superOnlineBanking"
            rules={[
              {
                required: true,
                message: '请输入开户银行',
              },
            ]}
          >
            <Select
              placeholder="请输入开户银行"
              optionFilterProp="label"
              showSearch
              style={{ width: 226 }}
              allowClear
            >
              {list.length &&
                list.map((d) => (
                  <Option
                    key={d.superOnlineBanking}
                    value={d.superOnlineBanking}
                    label={d.bankName}
                  >
                    <Tooltip title={d.bankName}>{d.bankName}</Tooltip>
                  </Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="银行卡号"
            name="bankNo"
            rules={[
              {
                required: true,
                message: '请输入正确的银行卡号',
              },
            ]}
          >
            <Input placeholder="请输入银行卡号" autoComplete="off" />
          </Form.Item>

          <Form.Item
            label="验证码"
            name="code"
            rules={[
              {
                required: true,
                message: '请输入正确的验证码!',
              },
            ]}
          >
            <Row gutter={8}>
              <Col span={12}>
                <Input placeholder="请输入验证码" />
              </Col>
              <Col span={12}>
                <Button
                  style={{ width: '109px' }}
                  disabled={second}
                  onClick={verification}
                >
                  {second ? `${second}s` : '获取验证码'}
                </Button>
              </Col>
            </Row>
          </Form.Item>
        </Form>
      );
    } else {
      return (
        <Form
          {...layout}
          name="pay-two"
          form={form}
          initialValues={{
            name: accountExtend?.licenseName,
            idNumber: accountExtend?.socialCreditCode,
            reprName: accountExtend?.userName,
            reprGlobalId: accountExtend?.idCard,
            phone: accountExtend?.mobile,
          }}
        >
          <div>
            <Form.Item
              label="营业执照名称"
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入营业执照名称',
                },
              ]}
            >
              <Input placeholder="请输入营业执照名称" />
            </Form.Item>

            <Form.Item
              label="社会统一信用代码"
              name="idNumber"
              rules={[
                {
                  required: true,
                  message: '请输入正确社会统一信用代码',
                },
              ]}
            >
              <Input placeholder="请输入社会统一信用代码" />
            </Form.Item>

            <Form.Item
              label="法人姓名"
              name="reprName"
              rules={[
                {
                  required: true,
                  message: '请输入法人姓名',
                },
              ]}
            >
              <Input placeholder="请输入法人姓名" />
            </Form.Item>

            <Form.Item
              label="身份证号"
              name="reprGlobalId"
              rules={[
                {
                  required: true,
                  message: '请输入法人身份证号',
                },
              ]}
            >
              <Input placeholder="请输入法人身份证号" />
            </Form.Item>

            <Form.Item
              label="银行预留手机号"
              name="phone"
              rules={[
                {
                  required: true,
                  // pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                  message: '请输入正确的手机号!',
                },
              ]}
            >
              <Input placeholder="请输入银行预留手机号" />
            </Form.Item>

            <Form.Item
              label="开户银行"
              name="superOnlineBanking"
              rules={[
                {
                  required: true,
                  message: '请输入开户银行',
                },
              ]}
            >
              <Select
                placeholder="请输入开户银行"
                optionFilterProp="label"
                showSearch
                style={{ width: 226 }}
                allowClear
              >
                {list.length &&
                  list.map((d) => (
                    <Option
                      key={d.superOnlineBanking}
                      value={d.superOnlineBanking}
                      label={d.bankName}
                    >
                      <Tooltip title={d.bankName}>{d.bankName}</Tooltip>
                    </Option>
                  ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="银行卡号"
              name="bankNo"
              rules={[
                {
                  required: true,
                  message: '请输入银行卡号',
                },
              ]}
            >
              <Row gutter={8}>
                <Col span={18}>
                  <Input placeholder="请输入银行卡号" />
                </Col>
                <Col span={6}>
                  <Button onClick={paymentOk}>确认打款</Button>
                </Col>
              </Row>
            </Form.Item>

            <Form.Item
              label="输入收款金额"
              name="authAmt"
              rules={[
                {
                  required: true,
                  message: '请输入收款金额!',
                },
              ]}
            >
              <Input placeholder="请输入收款金额" />
            </Form.Item>

            <Form.Item
              label="验证码"
              name="code"
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
              ]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>
          </div>
        </Form>
      );
    }
  };

  //获取验证码
  const code = async (val) => {
    list.map((item) => {
      if (item.superOnlineBanking == val.superOnlineBanking) {
        val.bankName = item.bankName;
        if (val.bankName == '平安银行') {
          val.bankType = 1;
        } else {
          val.bankType = 2;
        }
      }
    });
    //商户
    if (accountMsg.merchantNo) {
      val.accountNo = accountMsg.merchantNo;
      val.accountType = 2;
    }
    const res = await bankCode({
      ...val,
      indivBusinessFlag: '1',
    });
    if (res.success) {
      message.success('验证码发送成功!');
    }
  };

  //获取验证码点击校验倒数事件
  const verification = async () => {
    form
      .validateFields([
        'companyName',
        'companyGlobalId',
        'phoneNumber',
        'name',
        'idNumber',
        'bankNo',
        'superOnlineBanking',
        'phone',
      ])
      .then((value) => {
        let num = 59;
        setSecond(59);
        let seconds = setInterval(() => {
          num = num - 1;
          setSecond(num);
          if (num === 0) {
            clearInterval(seconds);
            setSecond(0);
          }
        }, 1000);
        code(value);
      });
  };

  //确认点击事件
  function PayModalVerify() {
    form
      .validateFields()
      .then(async (val) => {
        setSpinning(true);
        list.map((item) => {
          if (item.superOnlineBanking == val.superOnlineBanking) {
            val.bankName = item.bankName;
            if (val.bankName == '平安银行') {
              val.bankType = 1;
            } else {
              val.bankType = 2;
            }
          }
        });
        //商户
        if (accountMsg.merchantNo) {
          val.accountNo = accountMsg.merchantNo;
          val.accountType = 2;
        }
        val.bankNo = val.bankNo.replaceAll(' ', ''); //防止解绑找不到数据
        // 调用接口处
        if (type == 0) {
          const res = await bankCard({ ...val });
          if (res.success) {
            message.success('绑定银行卡成功');
            ModalCancel();
            setList([]);
            pageInit();
          }
        } else {
          const res = await paymentBinding({ ...val });
          if (res.success) {
            message.success('绑定银行卡成功');
            setList([]);
            ModalCancel();
            pageInit();
          }
        }
        let timer = setTimeout(() => {
          setSpinning(false);
          clearTimeout(timer);
          timer = null;
        }, 300);
      })
      .catch(() => {});
  }

  // 下一步
  const next = () => {
    form.validateFields().then((val) => {
      setType(val.type);
      setCurrent(1);
    });
  };

  // 上一步
  const prev = () => {
    setCurrent(0);
  };

  // 确认打款
  const paymentOk = () => {
    form
      .validateFields([
        'name',
        'idNumber',
        'bankNo',
        'superOnlineBanking',
        'phone',
        'reprGlobalId',
        'reprName',
      ])
      .then(async (val) => {
        list.map((item) => {
          if (item.superOnlineBanking == val.superOnlineBanking) {
            val.bankName = item.bankName;
            if (val.bankName == '平安银行') {
              val.bankType = 1;
            } else {
              val.bankType = 2;
            }
          }
        });
        if (accountMsg.merchantNo) {
          val.accountNo = accountMsg.merchantNo;
          val.accountType = 2;
        }
        const { success } = await payment({
          ...val,
        });
        if (success) {
          message.success('打款成功');
        }
      });
  };

  //取消弹框点击事件
  const ModalCancel = async () => {
    form.resetFields();
    setCurrent(0);
    bankCardClose();
  };

  return (
    <CommonModal
      title="绑定银行卡"
      visible={bankCardSwitch}
      onCancel={ModalCancel}
      footer={
        current == 0
          ? [
              <Button key={1} onClick={ModalCancel} loading={spinning}>
                取消
              </Button>,
              <Button
                key={2}
                disabled={isOldAccount ? true : false}
                type="primary"
                loading={spinning}
                onClick={next}
              >
                下一步
              </Button>,
            ]
          : [
              <Button key={1} onClick={prev} loading={spinning}>
                上一步
              </Button>,
              <Button
                key={2}
                type="primary"
                loading={spinning}
                onClick={PayModalVerify}
              >
                确定
              </Button>,
            ]
      }
    >
      <Steps current={current}>
        <Step title="选择类型" />
        <Step title="绑定银行卡" />
      </Steps>
      <div style={{ marginTop: 25 }}>
        {current == 0 ? (
          <Form
            {...layout}
            name="pay"
            form={form}
            initialValues={{
              type:
                !isOldAccount && Object.keys(accountExtend).length > 0
                  ? accountTypeMap[accountExtend?.accountType]
                  : '',
            }}
          >
            <div>
              <Form.Item
                label="绑定银行卡类型"
                name="type"
                rules={[
                  {
                    required: true,
                    message: '请选择绑定银行卡类型',
                  },
                ]}
              >
                <Radio.Group>
                  <Radio
                    disabled={
                      isOldAccount || accountExtend.accountType != 2
                        ? true
                        : false
                    }
                    value="0"
                  >
                    个体工商户法人卡
                  </Radio>
                  <Radio
                    disabled={
                      isOldAccount || accountExtend?.accountType != 3
                        ? true
                        : false
                    }
                    value="1"
                  >
                    企业
                  </Radio>
                </Radio.Group>
              </Form.Item>
              <div
                style={{
                  paddingLeft: '20px',
                  fontSize: '10px',
                  color: '#FF5F5F',
                }}
              >
                <span style={{ fontWeight: 700 }}>个体工商户法人卡免费</span>
                ，企业卡提现手续费：小于等于5万每笔6元，大于5万每笔10元
                <div>个人用户，目前无法绑卡</div>
              </div>
            </div>
          </Form>
        ) : (
          cardFrom()
        )}
      </div>
      <CommonLoading loading={spinning} />
    </CommonModal>
  );
};

export default BankCardModal;
